package com.jse.mvc;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Xmls;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.view.RawView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.jse.service.NashornService;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

@RestController
public class ToolsAction {

	@Autowired NashornService nashornService;
	
	@Autowired JdbcTemplate jdbcTemplate;

	@CrossOrigin(maxAge=3600,origins= "*",allowedHeaders="*",methods= {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE})
	@RequestMapping("/{key:^[A-Z]+$}")
    public Object url(@PathVariable String key,@RequestAttribute("p")NutMap p,HttpServletRequest req,HttpServletResponse resp){
		String sql="select url from url where key = ? ";
		Object rtv=jdbcTemplate.queryForObject(sql, String.class,key);
		return rtv;
    }
	
	@CrossOrigin(maxAge=3600,origins= "*",allowedHeaders="*",methods= {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE})
	@RequestMapping(value={"/json/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}",
			"/json/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}.json",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}.json"})
    public @ResponseBody void json(@PathVariable String jjs,@PathVariable String func,@RequestAttribute("p")NutMap p,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		Object obj=nashornService.run(jjs,func,p,req,resp);
		resp.setContentType("application/json;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");//
		resp.getWriter().write(Json.toJson(obj,JsonFormat.compact()));
    }
	@CrossOrigin(maxAge=3600,origins= "*",allowedHeaders="*",methods= {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE})
	@RequestMapping(value={"/jsonp/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}",
			"/jsonp/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}.jsonp",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}.jsonp"})
    public @ResponseBody void jsonp(@PathVariable String jjs,@PathVariable String func,@RequestAttribute("p")NutMap p,@RequestParam(name="callback",defaultValue="callback")String callback,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		Object obj=nashornService.run(jjs,func,p,req,resp);
		resp.setContentType("text/plain;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");//
		StringBuffer jsonp=new StringBuffer(callback);
		jsonp.append("(").append(Json.toJson(obj,JsonFormat.compact())).append(")");
		resp.getWriter().write(jsonp.toString());
    }
	@CrossOrigin(maxAge=3600,origins= "*",allowedHeaders="*",methods= {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE})
	@RequestMapping(value={"/txt/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}",
			"/txt/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}.txt",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}.txt"})
    public @ResponseBody void txt(@PathVariable String jjs,@PathVariable String func,@RequestAttribute("p")NutMap p,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		Object obj=nashornService.run(jjs,func,p,req,resp);
		resp.setContentType("text/plain;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");//
		resp.getWriter().write(obj.toString());
    }
	@CrossOrigin(maxAge=3600,origins= "*",allowedHeaders="*",methods= {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE})
	@RequestMapping(value={"/raw/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}",
			"/raw/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}.obj",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}.obj"})
    public @ResponseBody void raw(@PathVariable String jjs,@PathVariable String func,@RequestAttribute("p")NutMap p,HttpServletRequest req,HttpServletResponse resp) throws Throwable{
		Object obj=nashornService.run(jjs,func,p,req,resp);
		resp.setContentType("text/plain;charset=utf-8");
		if (obj instanceof File) {// 文件以及下载
			File f=(File) obj;
			String filename=URLEncoder.encode(f.getName(),"utf-8");
//			resp.reset();
			  resp.setCharacterEncoding("utf-8");  
			  resp.setHeader("Content-Disposition","attachment; filename="+filename);  
	            //获取响应报文输出流对象  
			  ServletOutputStream out=resp.getOutputStream();
			  out.write(org.nutz.lang.Files.readBytes(f));
			  out.flush();
			  out.close();
			return;
		}else {
			new RawView("text/plain").render(req, resp, obj);
		}
    }
	@SuppressWarnings("unchecked")
	@CrossOrigin(maxAge=3600,origins= "*",allowedHeaders="*",methods= {RequestMethod.GET,RequestMethod.POST,RequestMethod.PUT,RequestMethod.DELETE})
	@RequestMapping(value={"/xml/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}",
			"/xml/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}/{func:^[a-z][a-zA-Z0-9_]+$}.xml",
			"/{jjs:^[a-z][a-zA-Z0-9_]+$}-{func:^[a-z][a-zA-Z0-9_]+$}.xml"})
    public @ResponseBody void xml(@PathVariable String jjs,@PathVariable String func,@RequestAttribute("p")NutMap p,@RequestParam(name="entity",defaultValue="entity")String entity,HttpServletRequest req,HttpServletResponse resp) throws IOException{
		Object obj=nashornService.run(jjs,func,p,req,resp);
		resp.setContentType("application/json;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");//
		if (obj instanceof ScriptObjectMirror) {// 针对jjs的[object Array]类型转换
			ScriptObjectMirror som = ScriptObjectMirror.class.cast(obj);
			if (som.toString().equals("[object Array]")) {
				obj = Json.fromJson(ArrayList.class, Json.toJson(som));
			} else if (som.toString().equals("[object Object]")) {
				obj = NutMap.WRAP(som);
			}
		}
		if (obj instanceof Map) {
			resp.getWriter().write(Xmls.mapToXml(entity,(Map<String, Object>) obj));
		}else if (obj instanceof List) {
			resp.getWriter().write(Xmls.mapToXml(entity,NutMap.NEW().addv("list", obj)));
		}else if (obj instanceof File) {
			File f=(File) obj;
			resp.getWriter().write(new String(Files.readAllBytes(Paths.get(f.getAbsolutePath()))));
		}else if (obj instanceof String) {
			resp.getWriter().write(obj.toString());
		}else {
			resp.getWriter().write(Xmls.mapToXml(entity,(Map<String, Object>) obj));
		}
    }
}
